//
//  UserAccount.swift
//  Practice
//
//  Created by miaozhihui on 2016/12/21.
//  Copyright © 2016年 DeKuTree. All rights reserved.
//

import UIKit

private let accountFile: NSString = "userAccount.json"

/// 用户账户模型
//class UserAccount: NSObject,NSCoding {
class UserAccount: NSObject {
    
    /// 访问令牌
    var access_token:String?
    
    /// access_token的生命周期，单位是秒数
    var expires_in:TimeInterval = 0 {
        didSet {
            // 计算过期日期
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    /// 过期日期
    var expiresDate:Date?
    
    /// 用户id
    var uid:String?
    
    /// 用户昵称
    var screen_name:String?
    
    /// 用户头像地址（大图），180×180像素
    var avatar_large:String?
    
    override init() {
        super.init()
        // 从磁盘加载保存的文件
        guard let path = accountFile.xs_appendDocumentDir(),
            let data = NSData(contentsOfFile: path),
            let dict = try? JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers) as? [String:Any] else {
                return
        }
        
        // 使用保存的字典数据给模型赋值
        yy_modelSet(with: dict ?? [:])
        
//        expiresDate = Date(timeIntervalSinceNow: -3600*24)
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期")
            
            // 清空数据
            access_token = nil
            uid = nil
            screen_name = nil
            avatar_large = nil
            
            // 删除文件
            try? FileManager.default.removeItem(atPath: path)
        }
    }
//    init(dict:[String:Any]) {
//        super.init()
//        setValuesForKeys(dict)
//    }
//    
//    override func setValue(_ value: Any?, forUndefinedKey key: String) {
//        
//    }
    
    override var description: String {
        return yy_modelDescription()
//        let keys = ["access_token","expires_in","expiresDate","uid","screen_name","avatar_large"]
//        return dictionaryWithValues(forKeys: keys).description
    }
    
    func saveAccount() {
        // 模型转字典
        var dict = (self.yy_modelToJSONObject() as? [String:Any]) ?? [:]
        // 删除过期字段
        dict.removeValue(forKey: "expires_in")
        // 把字典转换成二进制数据(序列化)
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted),
            let filePath = accountFile.xs_appendDocumentDir() else {
                return
        }
        // 写入数据到文档
        (data as NSData).write(toFile: filePath, atomically: true)

        print("用户账户保存成功\(filePath)")
    }
    
    // MARK: - 归档和解档
    /// 归档 - 在把当前对象保存到磁盘前，将对象编码成二进制数据
    ///
    /// - Parameter aCoder: 编码器
//    func encode(with aCoder: NSCoder) {
//        aCoder.encode(access_token, forKey: "access_token")
//        aCoder.encode(expiresDate, forKey: "expiresDate")
//        aCoder.encode(uid, forKey: "uid")
//        aCoder.encode(screen_name, forKey: "screen_name")
//        aCoder.encode(avatar_large, forKey: "avatar_large")
//    }
    
    /// 解档 - 从磁盘加载二进制文件，转换成对象时调用
    ///
    /// - Parameter coder: 解码器
    /// - returns: 当前对象
//    required init?(coder aDecoder: NSCoder) {
//        access_token = aDecoder.decodeObject(forKey: "access_token") as? String
//        expiresDate = aDecoder.decodeObject(forKey: "expiresDate") as? Date
//        uid = aDecoder.decodeObject(forKey: "uid") as? String
//        screen_name = aDecoder.decodeObject(forKey: "screen_name") as? String
//        avatar_large = aDecoder.decodeObject(forKey: "avatar_large") as? String
//    }
}
